#version 110

uniform int num_lights;

vec4 lightIntensity( const vec3 grad ) {

	if(num_lights <= 0 || num_lights > 10)
	{
		return vec4(1, 1, 1, 1);
	}
	else
	{
		vec4 total_intensity = vec4(0, 0, 0, 1);
		for(int i = 0; i < gl_MaxLights; i++)
		{
			if(i == num_lights)
				break;

			vec3 lightDir = vec3(gl_LightSource[i].position);
			lightDir = normalize(lightDir);
			vec3 normal = normalize(grad);
			
			vec4 norm = vec4(normal.x, normal.y, normal.z, 1);
			norm = gl_ModelViewMatrixInverseTranspose * norm;
			norm = normalize(norm);
			normal = vec3(norm.x, norm.y, norm.z);
			normal = normalize(normal);

			const vec4 ambient = 0.2 * gl_Color;
			const vec4 diffuse = 0.8 * gl_Color;

			float dotProduct = dot(normal, lightDir);
			//if(dotProduct < 0.0) dotProduct = 0.0;//causes wrong behaviour - may be a driver bug
			dotProduct = max(0.0, dotProduct);
			vec4 intensity = (diffuse * dotProduct + ambient)/float(num_lights);
			total_intensity += intensity;
		}
		total_intensity.a = 1.0;
		return total_intensity;
	}
}